﻿using System.Web.Mvc;
using System.Web.Mvc.Html;
using System.Linq.Expressions;
using System.Web.Routing;

namespace System.Web.Mvc.Html
{
    public static class HtmlHelperExtensions
    {
        public static void RenderAction<TController>(this HtmlHelper htmlHelper,
            Expression<Action<TController>> operation)
            where TController : Controller
        {
            var controllerName = typeof(TController).Name;
            if (controllerName.EndsWith("Controller"))
            {
                controllerName = controllerName.Substring(0,
                    controllerName.Length - "Controller".Length);
            }

            var call = operation.Body as MethodCallExpression;
            if (call != null)
            {
                var actionName = call.Method.Name;
                var parameters = call.Method.GetParameters();
                if (parameters.Length > 0)
                {
                    var routeValues = new RouteValueDictionary();
                    for (int i = 0; i < parameters.Length; i++)
                    {
                        var ce = call.Arguments[i] as ConstantExpression;
                        if (ce != null)
                        {
                            routeValues.Add(parameters[i].Name, ce.Value);
                        }
                        else
                        {
                            var lambda = Expression.Lambda(call.Arguments[i],
                                                         operation.Parameters);
                            Delegate d = lambda.Compile();
                            var value = d.DynamicInvoke(new object[1]);
                            routeValues.Add(parameters[i].Name, value);
                        }

                    }
                    htmlHelper.RenderAction(actionName, controllerName, routeValues);
                }
                else
                {
                    htmlHelper.RenderAction(actionName, controllerName);
                }
            }
        }
    }

}
